package com.mcxx.redis.client;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.mcxx.redis.constant.RedisGlobalConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Component
public class RedisClusterUtils {

    public final String CACHE_PREFIX = "SOCIETY_CACHE:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ObjectTranscoder objectTranscoder;


    public boolean expire(String key, long time) {
        key = CACHE_PREFIX + key;
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public long getExpire(String key) {
        key = CACHE_PREFIX + key;
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    public boolean hasKey(String key) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public long del(String... key) {
        long count = 0;
        if(null == key || key.length == 0) {
            return count;
        }
        if (key.length == 1) {
            String keyStr = CACHE_PREFIX + key[0];
            if(redisTemplate.delete(keyStr)) {
                ++count;
            }
        }
        else {
            List<String> keyList = new ArrayList<>();
            CollectionUtils.arrayToList(key).forEach(i -> {
                i = CACHE_PREFIX + i;
                keyList.add(i.toString());
            });
            count = redisTemplate.delete(keyList);
        }
        return count;
    }


    public long del(List<String> keys) {
        long count = 0;
        if(CollectionUtil.isEmpty(keys)) {
            return count;
        }

        if (keys.size() == 1) {
            String keyStr = CACHE_PREFIX + keys.get(0);
            if(redisTemplate.delete(keyStr)) {
                ++count;
            }
        }
        else {
            List<String> keyList = new ArrayList<>();
            CollectionUtils.arrayToList(keys).forEach(i -> {
                i = CACHE_PREFIX + i;
                keyList.add(i.toString());
            });
            count = redisTemplate.delete(keyList);
        }
        return count;
    }




    public Object get(String key) {
        if(StringUtils.isEmpty(key)) {
            return null;
        }
        key = CACHE_PREFIX + key;
        return redisTemplate.opsForValue().get(key);
    }


    public boolean set(String key, Object value) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    public boolean set(String key, Object value, long time) {
        key = CACHE_PREFIX + key;
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public long incr(String key, long delta) {
        key = CACHE_PREFIX + key;
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }


    public long decr(String key, long delta) {
        key = CACHE_PREFIX + key;
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }




    public Object hget(String key, String item) {
        key = CACHE_PREFIX + key;
        return redisTemplate.opsForHash().get(key, item);
    }


    public <T> Map<String, T> hmget(String key) {
        key = CACHE_PREFIX + key;
        Map<Object, Object> objMap = redisTemplate.opsForHash().entries(key);
        if(MapUtil.isEmpty(objMap)) {
            return null;
        }
        byte[] content = object2Byte(objMap);
        return (Map<String, T>) objectTranscoder.deserialize(content);
    }


    public <T> boolean hmset(String key, Map<String, T> map) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public Set<String> hasKeys(String keyPart) {
        return redisTemplate.keys(CACHE_PREFIX + "*"+ keyPart +"*");
    }


    public <T> boolean hmset(String key, Map<String, T> map, long time) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean hset(String key, String item, Object value) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean hset(String key, String item, Object value, long time) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public void hdel(String key, Object... item) {
        key = CACHE_PREFIX + key;
        redisTemplate.opsForHash().delete(key, item);
    }


    public boolean hHasKey(String key, String item) {
        key = CACHE_PREFIX + key;
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    public double hincr(String key, String item, double by) {
        key = CACHE_PREFIX + key;
        return redisTemplate.opsForHash().increment(key, item, by);
    }


    public double hdecr(String key, String item, double by) {
        key = CACHE_PREFIX + key;
        return redisTemplate.opsForHash().increment(key, item, -by);
    }




    public Set<Object> sGet(String key) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public boolean sHasKey(String key, Object value) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public long sSet(String key, Object... values) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public long sSetAndTime(String key, long time, Object... values) {
        key = CACHE_PREFIX + key;
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public long sGetSetSize(String key) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public long setRemove(String key, Object... values) {
        key = CACHE_PREFIX + key;
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }



    public List<Object> lGet(String key, long start, long end) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public long lGetListSize(String key) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public Object lGetIndex(String key, long index) {
        key = CACHE_PREFIX + key;
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public boolean lSet(String key, Object value) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean lSet(String key, Object value, long time) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean lSet(String key, List<Object> value) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean lSet(String key, List<Object> value, long time) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean lUpdateIndex(String key, long index, Object value) {
        key = CACHE_PREFIX + key;
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public long lRemove(String key, long count, Object value) {
        key = CACHE_PREFIX + key;
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public byte[] object2Byte(Object obj) {
        byte[] content = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(obj);
            content = outputStream.toByteArray();
        } catch (IOException e) {
        }
        return content;
    }


    public void convertAndSend(String redisListenerName, Map<String, Object> param) {
        param.put(RedisGlobalConstant.HANDLER_NAME, redisListenerName);
        redisTemplate.convertAndSend(RedisGlobalConstant.REDIS_TOPIC_NAME, param);
    }
}
